package com.tedu.weibo.exception;

import com.tedu.weibo.result.JsonResult;
import com.tedu.weibo.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice//springmvc将当前类当作全局异常处理类
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    //@ResponseBody
    public JsonResult doHandlerRuntimeException(RuntimeException re){
        System.out.println("处理RuntimeException!!!");
        log.error(re.getMessage(),re);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ie){
        System.out.println("处理IllegalArgumentException!!!");
        log.error(ie.getMessage(),ie);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandlerThrowable(Throwable t){
        log.error(t.getMessage(),t);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException me){
        System.out.println("message:"+me.getFieldError().getDefaultMessage());
        String message = me.getFieldError().getDefaultMessage();

        log.error(me.getFieldError().getDefaultMessage(),me);
        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ce){
        System.out.println("message:"+ce.getMessage());

        String message = ce.getMessage();
        //message = message.substring(message.indexOf(":")+1).trim();
        StringBuilder builder = new StringBuilder(message);
        builder = builder.delete(0,message.indexOf(":")+2);

        System.out.println(builder);
        log.error(builder.toString(),ce);
        return new JsonResult(StatusCode.VALIDATE_ERROR,builder);
    }

}
